<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #alarmRange="{ model, field }">
        <div v-for="(item, index) in model[field]" :key="index" class="range-list">
          <Space class="input-box">
            <Form.Item :name="['alarmRangeList', index, 'deviceTypeId']">
              <Select v-model:value="item.deviceTypeId" placeholder="请选择设备类型"
                :field-names="{ label: 'name', value: 'id' }" @change="handleChangeRangeData" :options="typeList">
              </Select>
            </Form.Item>
            <Form.Item :name="['alarmRangeList', index, 'alarmTypeId']">
              <Select v-model:value="item.alarmTypeId" placeholder="请选择告警类型"
                :field-names="{ label: 'name', value: 'id' }" @change="handleChangeRangeData" :options="alarmList">
              </Select>
            </Form.Item>
          </Space>
          <Form.Item>
            <Space>
              <Button :icon="h(PlusOutlined)" @click="handleAddLine(index)"></Button>
              <Button :icon="h(MinusOutlined)" danger :disabled="model[field].length === 1"
                @click="handleRemoveLine(index)"></Button>
            </Space>
          </Form.Item>
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, reactive, watch } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form';
import { accountFormSchema } from './type.data';
import { getDataList } from '@/api/demo/collection';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons-vue';
import { getRoleList } from '@/api/sys/system';
import { formItemsForEach } from '../../form-design/utils';
import { getAlarmTypeList, alarmRecordAdd, alarmRecordUpdate } from '@/api/alarm/alarm'
import { getDeviceTypeList } from '@/api/collection/device'
import { Select, Space, Form, Button } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';


defineOptions({ name: 'AlarmModal' });

const emit = defineEmits(['success', 'register']);

const isUpdate = ref(true);
const rowId = ref('');

// 设备类型options
const typeList = ref([])
//  告警类型options
const alarmList = ref([])

const [registerForm, { setFieldsValue, getFieldsValue, validateFields,
  updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    const alarmRuleRoleVOList = data.record?.alarmRuleRoleVOList ? data.record.alarmRuleRoleVOList.map(item => item.roleId) : []
    rowId.value = data.record.id;
    setFieldsValue({
      ...data.record,
      alarmRuleRoleVOList,
    });
  }
  await getDeviceTypeData()
  await getAlarmTypeData()
  const roleList = await getRoleList()

  updateSchema([
    {
      field: 'alarmRuleRoleVOList',
      componentProps: {
        options: unref(roleList),
      },
    },
  ]);
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增告警项' : '修改告警项'));

async function handleChangeRangeData() {
  validateFields(['alarmRangeList'])
}

// 适用范围添加一行
function handleAddLine(index) {
  const { alarmRangeList } = getFieldsValue()
  const newData = cloneDeep(alarmRangeList)
  newData.splice(
    index + 1,
    0,
    {
      deviceTypeId: undefined,
      alarmTypeId: undefined,
    }
  )
  setFieldsValue({
    alarmRangeList: newData
  })
}
// 移除一行
function handleRemoveLine(index) {
  const { alarmRangeList } = getFieldsValue()
  const newData = cloneDeep(alarmRangeList)
  newData.splice(index, 1)
  setFieldsValue({
    alarmRangeList: newData
  })
}

// 获取设备类型
async function getDeviceTypeData() {
  const data = await getDeviceTypeList({})
  typeList.value = data
}

// 获取告警类型
async function getAlarmTypeData() {
  const data = await getAlarmTypeList()
  alarmList.value = data
}

async function handleSubmit() {
  try {
    const values = await validate();
    const alarmRuleRoleVOList = values.alarmRuleRoleVOList.map(item => ({
      roleId: item.value,
      roleName: item.label
    }))
    const data = { ...values, alarmRuleRoleVOList }
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      const params = { ...data, id: rowId.value }
      await alarmRecordUpdate(params)
    } else {
      await alarmRecordAdd(data)
    }
    closeModal();
    emit('success', { isUpdate: unref(isUpdate), values: { ...data, id: rowId.value } });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
<style lang="scss">
.range-list {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;

  &:last-child {
    .ant-form-item {
      margin-bottom: 0;
    }
  }

  .input-box {
    flex: 1;
    margin-right: 8px;

    .ant-space-item {
      flex: 1;
    }
  }
}
</style>
